<template>
  <div class="register-container">
    <div class="register-header">
      <h1 class="app-title">注册新用户</h1>
      <button class="back-btn" @click="$router.push('/login')">
        返回登录
      </button>
    </div>

    <form @submit.prevent="handleRegister" class="register-form">
      <div class="message" :class="messageClass" v-if="message">
        {{ message }}
      </div>

      <div class="form-item">
        <label>用户名:</label>
        <div class="input-group">
          <input 
            type="text" 
            v-model="form.username" 
            placeholder="请输入用户名（3-50个字符）" 
            required
            @blur="checkUsername"
            :class="{ 'error': usernameError }"
          />
          <button 
            type="button" 
            class="check-btn"
            @click="checkUsername"
            :disabled="checking"
          >
            {{ checking ? '检查中...' : '检查' }}
          </button>
        </div>
        <div class="error-msg" v-if="usernameError">{{ usernameError }}</div>
      </div>

      <div class="form-item">
        <label>昵称:</label>
        <input 
          type="text" 
          v-model="form.nickname" 
          placeholder="请输入昵称" 
          required
        />
      </div>

      <div class="form-item">
        <label>密码:</label>
        <div class="password-input">
          <input 
            :type="showPassword ? 'text' : 'password'" 
            v-model="form.password" 
            placeholder="请输入密码（至少6位）" 
            required
            @blur="validatePassword"
            :class="{ 'error': passwordError }"
          />
          <button 
            type="button" 
            class="eye-icon" 
            @click="showPassword = !showPassword"
          >
            {{ showPassword ? '👁️' : '👁️' }}
          </button>
        </div>
        <div class="error-msg" v-if="passwordError">{{ passwordError }}</div>
      </div>

      <div class="form-item">
        <label>确认密码:</label>
        <input 
          :type="showConfirmPassword ? 'text' : 'password'" 
          v-model="form.confirmPassword" 
          placeholder="请再次输入密码" 
          required
          @blur="validateConfirmPassword"
          :class="{ 'error': confirmPasswordError }"
        />
        <div class="error-msg" v-if="confirmPasswordError">{{ confirmPasswordError }}</div>
      </div>

      <div class="form-item">
        <label>手机号 (可选):</label>
        <input 
          type="tel" 
          v-model="form.phone" 
          placeholder="请输入11位手机号"
          @blur="validatePhone"
          :class="{ 'error': phoneError }"
        />
        <div class="error-msg" v-if="phoneError">{{ phoneError }}</div>
      </div>

      <div class="form-item">
        <label>邮箱 (可选):</label>
        <input 
          type="email" 
          v-model="form.email" 
          placeholder="请输入邮箱地址"
          @blur="validateEmail"
          :class="{ 'error': emailError }"
        />
        <div class="error-msg" v-if="emailError">{{ emailError }}</div>
      </div>

      <button type="submit" class="register-button" :disabled="loading || !canSubmit">
        {{ loading ? '注册中...' : '注册' }}
      </button>

      <div class="form-links">
        <span>已有账号？</span>
        <router-link to="/login" class="link-text">立即登录</router-link>
      </div>
    </form>

    <div class="terms">
      <span class="checkbox">☑</span>
      <span class="terms-text">
        注册即代表你同意
        <a href="#" class="link">《用户协议》</a>
        <a href="#" class="link">《隐私保护指引》</a>
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const checking = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

const message = ref('')
const messageClass = ref('')
const usernameError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const phoneError = ref('')
const emailError = ref('')

const form = ref({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})

const canSubmit = computed(() => {
  return form.value.username && 
         form.value.nickname && 
         form.value.password && 
         form.value.confirmPassword &&
         form.value.password === form.value.confirmPassword &&
         !usernameError.value &&
         !passwordError.value &&
         !confirmPasswordError.value
})

const validatePassword = () => {
  if (form.value.password.length < 6) {
    passwordError.value = '密码至少需要6位'
  } else {
    passwordError.value = ''
  }
}

const validateConfirmPassword = () => {
  if (form.value.password !== form.value.confirmPassword) {
    confirmPasswordError.value = '两次输入的密码不一致'
  } else {
    confirmPasswordError.value = ''
  }
}

const validatePhone = () => {
  if (form.value.phone && !/^1[3-9]\d{9}$/.test(form.value.phone)) {
    phoneError.value = '请输入正确的11位手机号'
  } else {
    phoneError.value = ''
  }
}

const validateEmail = () => {
  if (form.value.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.value.email)) {
    emailError.value = '请输入正确的邮箱地址'
  } else {
    emailError.value = ''
  }
}

const checkUsername = async () => {
  if (!form.value.username) {
    usernameError.value = '请输入用户名'
    return
  }

  if (form.value.username.length < 3 || form.value.username.length > 50) {
    usernameError.value = '用户名长度必须在3-50个字符之间'
    return
  }

  checking.value = true
  try {
    const response = await axios.get('/api/auth/check-username', {
      params: { username: form.value.username }
    })
    
    if (response.data.available) {
      usernameError.value = ''
    } else {
      usernameError.value = response.data.message
    }
  } catch (error) {
    usernameError.value = '检查失败，请重试'
  } finally {
    checking.value = false
  }
}

const handleRegister = async () => {
  // 验证
  validatePassword()
  validateConfirmPassword()
  validatePhone()
  validateEmail()
  
  if (!canSubmit.value) {
    message.value = '请完善注册信息'
    messageClass.value = 'error'
    return
  }

  loading.value = true
  message.value = ''
  
  try {
    const formData = new FormData()
    formData.append('username', form.value.username)
    formData.append('password', form.value.password)
    formData.append('nickname', form.value.nickname)
    if (form.value.phone) formData.append('phone', form.value.phone)
    if (form.value.email) formData.append('email', form.value.email)
    
    const response = await axios.post('/api/auth/register', formData)
    
    if (response.data.success) {
      message.value = '注册成功！正在跳转到登录页面...'
      messageClass.value = 'success'
      
      // 保存用户信息
      localStorage.setItem('user_id', response.data.user_id)
      localStorage.setItem('username', response.data.username)
      
      // 2秒后跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else {
      message.value = response.data.message || '注册失败'
      messageClass.value = 'error'
    }
  } catch (error) {
    message.value = error.response?.data?.message || '注册失败，请重试'
    messageClass.value = 'error'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  width: 100vw;
  min-height: 100vh;
  background: #fff;
  padding: 20px;
}

.register-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.app-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.back-btn {
  background: #007AFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.register-form {
  max-width: 400px;
  margin: 0 auto;
}

.message {
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-size: 14px;
  text-align: center;
}

.message.success {
  background: #d4edda;
  color: #155724;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.form-item input {
  width: 100%;
  padding: 12px;
  border: none;
  border-bottom: 2px solid #e0e0e0;
  font-size: 16px;
  outline: none;
  transition: border-color 0.3s;
}

.form-item input:focus {
  border-bottom-color: #007AFF;
}

.form-item input.error {
  border-bottom-color: #dc3545;
}

.input-group {
  display: flex;
  gap: 10px;
}

.input-group input {
  flex: 1;
}

.check-btn {
  background: #007AFF;
  color: white;
  border: none;
  padding: 12px 20px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
}

.check-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.password-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.password-input input {
  flex: 1;
}

.eye-icon {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
}

.error-msg {
  color: #dc3545;
  font-size: 12px;
  margin-top: 5px;
}

.register-button {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  margin-top: 20px;
  transition: transform 0.2s;
}

.register-button:hover:not(:disabled) {
  transform: translateY(-2px);
}

.register-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.form-links {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.link-text {
  color: #007AFF;
  text-decoration: none;
  margin-left: 5px;
}

.terms {
  position: fixed;
  bottom: 20px;
  left: 20px;
  right: 20px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.checkbox {
  color: #ff6b6b;
  font-size: 16px;
}

.terms-text {
  flex: 1;
}

.link {
  color: #007AFF;
  text-decoration: none;
}
</style>

